<?php
    class iJDataBaseResult {
        private $db_class;
        private $sql_query;
        private $sql_resource;
        private $result;
        private $query_found_rows;
        private $pages_count;
        
       

        /**
         *
         * This function is construct database result
         *
         * @param object $db_class - object of class database
         *
         * @access public
         */
        public function __construct(&$db_class = null) {
            $this->db_class =& $db_class;
        }
        
        
        /**   
         *
         * This function for set query
         *
         * @param string $query - query sql
         *
         * @access public
         */
        public function setQuery($query){
            $this->sql_query = $query;
            
        }
        
        /**
         *
         * Executing current query
         *
         * @return result of query
         *
         * @access public
         */
        public function execute($escape = false) {
            
            // Actually running the query
            if($escape) {
              $this->sql_resource = $this->db_class->simpleQuery(mysql_real_escape_string($this->sql_query));
            } else {
              $this->sql_resource = $this->db_class->simpleQuery($this->sql_query);
            }
            
            if($this->sql_resource === false) {
                $this->db_class->setError(mysql_error($this->db_class->getLink()), mysql_errno($this->db_class->getLink()), $this->sql_query);
            }
        }
        
        /**
         * Getting table size
         *
         * @param string $tableName  - table name
         * @return int - nmber og table rows
         *
         * @access public
         */
        public function getSize($select_field = '*') {
            if (stripos($this->sql_query, 'SQL_CALC_FOUND_ROWS') !== false) {
                $size = $this->db_class->simpleQuery('SELECT found_rows() AS total');
                
            } else {
                $total_query = substr($this->sql_query, 0, stripos($this->sql_query, ' LIMIT '));
                $pos_to      = strlen($total_query);
                $pos_from    = stripos($total_query, ' FROM ');
                $size = $this->db_class->simpleQuery('SELECT count(' . $select_field . ') AS total ' . substr($total_query, $pos_from, ($pos_to - $pos_from)));
            }
           // svd('SELECT count(' . $select_field . ') AS total ' . substr($total_query, $pos_from, ($pos_to - $pos_from)));
           // die();
            $res = $this->db_class->next($size);
            $this->query_found_rows = $res['total'];
            return $this->query_found_rows;
        }
        
        public function getPagesCount($limit = RESULT_LIMIT) {
            $this->pages_count = ceil($this->query_found_rows/$limit);
            return $this->pages_count;
        }
        
        public function getNextLink($page, $page_key, $get = null) {
          if(!is_array($get)) {
            $get =  array();
          } else {
            if(isset($get['keyword'])) {
              unset($get['keyword']);
            }
          }
          if($page >= $this->pages_count) {
            return iJHrefLink::linkToLocalPage('', iJHrefLink::Icon('next_disabled', '32x32'));
          } else {
            $get['page'] = $page + 1;
            return  iJHrefLink::linkToLocalPage($page_key, iJHrefLink::Icon('next', '32x32'), $get);
          }
        }
        
        
        public function getPerviousLink($page, $page_key, $get = null) {
          if(!is_array($get)) {
            $get =  array();
          } else {
            if(isset($get['keyword'])) {
              unset($get['keyword']);
            }
          }
          if($page <= 1) {
            return iJHrefLink::linkToLocalPage('', iJHrefLink::Icon('previous_disabled', '32x32'));
          } else {
            $get['page'] = $page - 1;
            return iJHrefLink::linkToLocalPage($page_key, iJHrefLink::Icon('previous', '32x32'), $get);
          }
        }
        
        /**
         *
         * This function for get next value of result query
         *
         * @access public
         */
        public function next() {
        
          $this->result = $this->db_class->next($this->sql_resource); 
          return $this->result;
          
        }
        
        /**
         *
         * Get number of rows in result
         *
         * @access public
         */
        public function numberOfRows() {
        
          $this->result = $this->db_class->numberOfRows($this->sql_resource); 
          return $this->result;
          
        }
        
        /**
         *
         * The function returns a result query as an array
         *
         * @access public
         */
        public function toArray() {
          if (!isset($this->result)) {
            $this->next();
          }
    
          return $this->result;
        }
        
        
        /**
         *
         * Bind mixed value
         *
         * @param string $place_holder - placeholder
         * @param mixed $value - value
         *
         * @access public
         */
        public function bindValue($place_holder, $value, $type = 'string', $trim = true) {
             if ($trim && !is_null($value)) {
                $value = trim($value);
              }
        
              if (is_null($value)) {
                $value = 'NULL';
              } else {
                switch ($type) {
                  case 'int':
                    $value = intval($value);
                    break;
                  case 'float':
                    $value = floatval($value);
                    break;
                  case 'string':
                  default:
                    $value = "'" . $value . "'";
                }
              }
            $this->bindReplace($place_holder, $value);
        
        }
        
        /**
         * bindTable
         *
         * This function for bind table
         *
         * @param string $place_holder - placeholder
         * @param string $value - name of table
         *
         * @access public
         */
        public function bindTable($place_holder, $value) {
          $this->bindReplace($place_holder, $value);
        }
        
                        
        public function bindLaguageDefinitions($place_holder, $table_name,  $psev) {
            $iJLanguages =  iJFactory::singleton('iJLanguages');
            $value = 'LEFT JOIN ' . TABLE_LANGUAGES_DEFINITIONS . ' AS def ON def.rowID = ' . $psev . ".id
                      WHERE def.tableName = '" . $table_name . "' AND def.langCode = '" . $iJLanguages->getLangCode() . "'";
            $this->bindReplace($place_holder, $value);
        }
        
        
        /**
         *
         * Gets the column value
         * @param $column - column name
         *
         * @access public
         */
        public function value($column) {
            
          if (isset($this->result[$column])) {
            return $this->result[$column];
          } else {
            return null;
          }
            
        }
        
    /**
     *
     * This function for replace symbols in value
     *
     * @param string $place_holder - placeholder
     * @param mixed $value - value
     *
     * @access public
     */
    public function bindReplace($place_holder, $value) {
      $pos = strpos($this->sql_query, $place_holder);

      if ($pos !== false) {

        $value           = str_replace('\\', '\\\\', $value);
        $this->sql_query = preg_replace('/'.$place_holder.'(\s+|[ ,)"]+|$)/s', "$value$1" ,$this->sql_query);
      }

    }
    
    
    /**
     *
     * Append Sql query
     *
     * @param string $sql_query - sql query part
     *
     * @access public
     */
     
    public function appendQuery($sql_query) {
        $this->sql_query = $this->sql_query . ' ' . $sql_query;
    }       
            
    
    
    /**
     *
     * Free result memory
     *
     * @param $resource - The result resource that is being evaluated. This result comes from a call to mysql_query().
     *
     * @return Returns TRUE on success or FALSE on failure.
     *
     * @access public
     */
    public function freeResult($resource) {
      if (@mysql_free_result($resource)) {
        return true;
      } else {
        $this->setError('Resource \'iDatabase->' . $resource . '\' could not be freed.');

        return false;
      }
    }
    
    public function addLimit($page, $limit = '') {
        if(empty($limit)) {
            $limit = RESULT_LIMIT;
        }
        
        return 'LIMIT ' . ($page-1) * $limit . ', ' . $limit;
        
        
    }
    
    
        
    }
?>